package com.jp.knowledge.adapter;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.jp.knowledge.R;
import com.jp.knowledge.model.HeadLine;

import java.util.List;

/**
 * Created by jiayen on 16/10/29.
 */

public class AttentionAdapter extends  RecyclerView.Adapter<RecyclerView.ViewHolder> implements View.OnClickListener {
    private List<HeadLine> headLines;
    private Context mContext;

    private int lastPosition;

    private int itemWidth;

    private OnItemSelect  onItemSelect;


    public void setOnItemSelect(OnItemSelect onItemSelect) {
        this.onItemSelect = onItemSelect;
    }

    public AttentionAdapter(List<HeadLine>  headLines, Context mContext){
        this.headLines=headLines;
        this.mContext=mContext;
    }
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(mContext).inflate(R.layout.top_item_view,parent,false);
        TopicAdpter.Viewholder viewholder = new TopicAdpter.Viewholder(view);
        view.setOnClickListener(this);
        return viewholder;
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        TextView name = (TextView) holder.itemView.findViewById(R.id.item);
        name.setText(headLines.get(position).getTypeName());
        holder.itemView.setTag(position);
        if(itemWidth==0){
            itemWidth=holder.itemView.getWidth();
        }
        if(headLines.get(position).isCheck()){
            name.setTextColor(mContext.getResources().getColor(R.color.theme_color));
            holder.itemView.findViewById(R.id.under_line).setVisibility(View.VISIBLE);
        }else{
            name.setTextColor(mContext.getResources().getColor(R.color.font_black_think));
            holder.itemView.findViewById(R.id.under_line).setVisibility(View.GONE);
        }
    }


    public void update(List<HeadLine> headLines){
        this.headLines=headLines;
        notifyDataSetChanged();
    }

    @Override
    public int getItemCount() {
        return headLines==null?0:headLines.size();
    }

    public void update(int position){
        if(position!=lastPosition) {//防止重复点击
            headLines.get(position).setCheck(true);
            headLines.get(lastPosition).setCheck(false);
            if(onItemSelect!=null)
                onItemSelect.onItemSelect(position);
        }
        lastPosition=position;
        notifyDataSetChanged();
    }

    @Override
    public void onClick(View view) {
        int position = (int) view.getTag();
        update(position);
    }

    public int getItemWidth(){
        return itemWidth;
    }

    public  interface  OnItemSelect{
        void onItemSelect(int position);
    }
}